package com.lwj.test.thread;

import java.util.LinkedList;

public class ReadWrite {

    private LinkedList<Object> shareList = new LinkedList<Object>();
    private int MAX = 10;

    public ReadWrite() {

    }

    public void start() {
	Thread readThread = new Thread(new Read());
	Thread writeThread = new Thread(new Write());
	readThread.start();
	writeThread.start();
	/*
	 * try { readThread.join(); writeThread.join(); } catch
	 * (InterruptedException e) { e.printStackTrace(); }
	 */
    }

    class Read implements Runnable {

	public void run() {
	    synchronized (shareList) {
		try {
		    if (shareList.size() == MAX) {
			System.out.println("full full !!!");
			shareList.wait();
		    }
		    for (int i = 0; i < MAX; i++) {
			Object o = new Object();
			shareList.add(o);
			System.out.println("add:" + i);
		    }
		    System.out.println("add object!!!  " + shareList.size());
		    shareList.notify();
		    // Thread.sleep(500);
		} catch (InterruptedException e) {
		    e.printStackTrace();
		}
	    }
	}

    }

    class Write implements Runnable {

	public void run() {
	    synchronized (shareList) {
		try {
		    if (shareList.size() == 0) {
			System.out.println("empty empty !!!");
			shareList.wait();
		    }
		    for (int j = 0, len = shareList.size(); j < len; j++) {
			shareList.remove();
			System.out.println("remove:" + j);
		    }
		    System.out.println(" remove object!!! " + shareList.size());
		    shareList.notify();
		    // Thread.sleep(500);
		} catch (InterruptedException e) {
		    e.printStackTrace();
		}
	    }
	}

    }
}
